/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.skywalking.apm.plugin.ice.v3;

import java.lang.reflect.Method;
import java.util.Map;

import com.zeroc.Ice.Endpoint;
import com.zeroc.IceInternal.OutgoingAsync;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.CarrierItem;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.OfficialComponent;

/**
 * <p> IceV3Interceptor
 *
 * @author gaochuan
 * @version 0.1.0
 * @date 2022/1/28 15:16
 * @since 2022/1/28
 */

public class IceV3ExecuteInterceptor implements InstanceMethodsAroundInterceptor {

    private static final ILog LOGGER = LogManager.getLogger(IceV3ExecuteInterceptor.class);

    /**
     * 方法执行前执行
     *
     * @param objInst
     * @param method
     * @param allArguments
     * @param argumentsTypes
     * @param result
     * @throws Throwable
     */
    @Override
    public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
                             Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {

        LOGGER.trace("IceV3ExecuteInterceptor.beforeMethod EnhancedInstance  :{}", (OutgoingAsync) objInst);
        OutgoingAsync outgoingAsync = (OutgoingAsync) objInst;

        String host = "";
        host = exactHost(outgoingAsync, host);
        String operationName = outgoingAsync.getOperation();
        //判断参数
        if (allArguments[0] == null || allArguments[1] == null) {
            // illegal args, can't trace. ignore.
            return;
        }
        //获取carrier
        ContextCarrier contextCarrier = new ContextCarrier();
        //创建exit span
        AbstractSpan span = ContextManager.createExitSpan(operationName, contextCarrier, host);
        LOGGER.trace("global trace id :{}", ContextManager.getGlobalTraceId());
        //获取传递ctx
        Map<String, String> ctx = (Map<String, String>) allArguments[1];
        LOGGER.trace("IceV3ExecuteInterceptor.beforeMethod process param :{}", allArguments);

        CarrierItem next = contextCarrier.items();
        LOGGER.trace("IceV3ExecuteInterceptor.beforeMethod next= headkey :{},headvalue :{}", next.getHeadKey(), next.getHeadValue());
        while (next.hasNext()) {
            //传递给下一个服务
            next = next.next();
            ctx.put(next.getHeadKey(), next.getHeadValue());
            LOGGER.trace("IceV3ExecuteInterceptor.beforeMethod afer hasnext next= headkey :{},headvalue :{}", next.getHeadKey(), next.getHeadValue());
        }
        span.setComponent(new OfficialComponent(115, "ice-java"));
        Tags.URL.set(span, host + "/" + operationName);
        SpanLayer.asRPCFramework(span);
    }

    private String exactHost(OutgoingAsync outgoingAsync, String host) {
        Endpoint[] endpoints = outgoingAsync.getProxy().ice_getEndpoints();
        if (null != endpoints && endpoints.length > 0) {
            String objectPrx = endpoints[0]._toString();
            //       "tcp -h skywalking-springboot-server -p 10006 -t 60000"
            String[] infos = objectPrx.split(" ");
            if (infos.length > 0) {
                int i = 0;
                for (String info : infos) {
                    i++;
                    if (info.equals("-h") && i < infos.length) {
                        host = infos[i];
                        break;
                    }
                }
            }
        }
        return host;
    }

    @Override
    public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
                              Class<?>[] argumentsTypes, Object ret) throws Throwable {
        LOGGER.trace("IceV3ExecuteInterceptor.afterMethod process");
        ContextManager.stopSpan();
        return ret;
    }

    @Override
    public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
                                      Class<?>[] argumentsTypes, Throwable t) {
        LOGGER.trace("IceV3ExecuteInterceptor.handleMethodException process");
        AbstractSpan activeSpan = ContextManager.activeSpan();
        activeSpan.log(t);
        activeSpan.errorOccurred();
    }
}
